package com.coder.algorithm.struct

/**
 * 单链表节点
 *
 * @author yuhus
 * @date: 2022/4/7
 */
data class ListNode(var value: Int) {
    var `val`: Int = value
    var next: ListNode? = null

    constructor(value: Int, next: ListNode? = null) : this(value) {
        this.next = next
    }

    fun toList(): ArrayList<Int> {
        return toList(this)
    }

    companion object {
        /**
         * 根据数组创建链表
         */
        fun create(data: IntArray): ListNode? {
            var tail: ListNode? = null
            for (i in data.size - 1 downTo 0) {
                tail = ListNode(data[i], tail)
            }
            return tail
        }

        /**
         * 添加头节点
         *
         * @return 头节点
         */
        fun addHead(head: ListNode, value: Int): ListNode {
            val cur = ListNode(value)
            cur.next = head.next
            head.next = cur
            return cur
        }

        /**
         * 添加尾节点
         *
         * @return 尾节点
         */
        fun addTail(head: ListNode, value: Int): ListNode? {
            val tail = ListNode(value)
            var cur = head
            while (cur.next != null) {
                cur = cur.next!!
            }
            cur.next = tail
            return tail
        }

        fun remove(head: ListNode, value: Int): ListNode? {
            // 创建哨兵节点
            var dummy = ListNode(-1, head)
            var prev: ListNode = dummy
            // 当前节点
            while (prev.next != null) {
                if (prev.next!!.value == value) {
                    prev.next = prev.next!!.next
                } else {
                    prev = prev.next!!
                }
            }
            return dummy.next
        }

        fun toList(head: ListNode?): ArrayList<Int> {
            val list = ArrayList<Int>()
            var cur: ListNode? = head
            while (cur != null) {
                list.add(cur.value)
                cur = cur.next
            }
            return list
        }
    }
}